package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.trouble.R
import com.spark.trouble.model.RespUnitModel
import com.spark.trouble.model.TroubleDealListModel
import kotlinx.android.synthetic.main.frag_major_risk.*

/**
 * 重大隐患
 */
class MajorRiskFragment : BaseFragment() {
    private var prop: TroubleDealListModel.ResultMap? = null
    private var propString: String = ""

    private val reqUnit = 0x1002
    private var respUnitModel: RespUnitModel.ResultMap? = null

    companion object {
        fun newInstance(prop: String): MajorRiskFragment {
            val target = MajorRiskFragment()
            val args = Bundle()
            args.putString("prop", prop)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_major_risk
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("prop")?.apply {
                propString = this
                prop = Gson().fromJson(this, TroubleDealListModel.ResultMap::class.java)
                LogUtils.e("prop >>> $prop")
            }
        }
        tv_approve_man.setOnClickListener {
            //parentFragment?.let { it as SupportFragment }?.startForResult(ChooseChoiceFragment.newInstance(ChooseChoiceFragment.unit), reqUnit)
        }
        btn_submit.setOnClickListener { submitCheck() }
        savedInstanceState?.apply {
            propString = getString("prop")
            prop = Gson().fromJson(propString, TroubleDealListModel.ResultMap::class.java)
        }
        fetchChkMan()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putString("prop", propString)
        super.onSaveInstanceState(outState)
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        when (requestCode) {
            reqUnit -> {
                if (resultCode == ChooseChoiceFragment.resUnit) {
                    data?.apply {
                        Gson().fromJson(getString("unit"), RespUnitModel.ResultMap::class.java)?.apply {
                            respUnitModel = this
                            tv_approve_man.text = this.acceptanceInfo.name
                        }
                    }
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun submitCheck() {
        val reason = et_reason.string()
        if (reason.isNullOrBlank()) {
            alert("请输入升级理由")
            return
        }
        val approveMan = tv_approve_man.text.toString().trim()
        if (approveMan.isNullOrBlank()) {
            alert("请选择审核人")
            return
        }
        val params = mutableMapOf(
                "taskId" to (prop?.task_id ?: ""),
                "fatalReason" to reason,
                "solutionTime" to sdf().format(System.currentTimeMillis())
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_major_upgrade_submit}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, UpgradeHTResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                } else {
                                    error("提交失败")
                                }
                                activity?.finish()
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    @SuppressLint("CheckResult")
    private fun fetchChkMan() {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_upgrade_chk_man}", "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ChkManModel::class.java)?.apply {
                                if (code == "200") {
                                    if (resultMaps.isNotEmpty()) {
                                        tv_approve_man.text = resultMaps[0].approverName
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }

    /**
     * @param approveState 审核状态 1 -> 驳回 2 -> 通过
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyVerify(taskId: String, approveState: String) {
        val params = mutableMapOf(
                "taskId" to taskId,
                "approveState" to approveState
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_major_submit_verify}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    /**
     * 待审核/待存储
     */
    @SuppressLint("CheckResult")
    private fun fetchVerifySave(taskId: String){
        Http.request()
                .rxPost("${Const.base_url}${Const.act_major_fetch_verify_save}", mutableMapOf("taskId" to taskId).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }
}


data class UpgradeHTResultModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var approverName: String = "" // 闫老师
    )
}


data class ChkManModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var approverName: String = "" // 闫老师
    )
}